package com.shanghaionstar.nav;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.BaseFragment;
import com.onstar.cn.map.common.PoiItemInfo;
import com.onstar.cn.weight.CustomBtnDrawableRightCenter;
import com.onstar.cn.weight.CustomImageView;
import com.onstar.cn.weight.DeleteEditText;
import com.onstar.cn.weight.ProgressLayout;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.VehicleLoadingActivity;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.enumtype.MapListViewType;
import com.shanghaionstar.nav.adapter.NavSearchTypeFragmentAdapter;
import com.shanghaionstar.nav.iview.INavSearchTypeView;
import com.shanghaionstar.nav.presenter.NavSearchTypePresenter;
import com.shanghaionstar.nav.service.AbstractMapActivity;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.MapHandler;
import com.shanghaionstar.weight.AddMoreView;

import java.util.List;

/**
 * Created by 6335yz on 2016/7/13.
 */
public class NavSearchTypeFragment extends BaseFragment implements INavSearchTypeView {

    @Override
    public void setLoading(boolean isLoading) {
        int visible = isLoading ? View.VISIBLE : View.GONE;
        package_list_progress.setVisibility(visible);
    }

    @Override
    public void onResponseError(OnStarException e) {
        AlertDialogUtil.showAlertDialog(mapActivity, getString(R.string.dialog_warning), e.getMessage());
    }

    @Override
    public void onReponseSuccess(Object object) {

    }

    @Override
    public Activity onActivity() {
        return null;
    }

    //    private Context context;
    private LogManager log = LogManager.getInstance(getActivity());

    @FindViewById(R.id.frame_back)
    private RelativeLayout frame_back;
    @FindViewById(R.id.edit_search_addressinfo)
    private DeleteEditText edit_search_addressinfo;
    @FindViewById(R.id.right_btn)
    private CustomImageView right_btn;

    @FindViewById(R.id.search_view)
    private LinearLayout search_view;
    //搜索范围
    @FindViewById(R.id.btn_regionalism)
    private CustomBtnDrawableRightCenter btn_regionalism;
    //排序
    @FindViewById(R.id.btn_sort)
    private CustomBtnDrawableRightCenter btn_sort;

    @FindViewById(R.id.search_type_listview)
    private ListView search_type_listview;
    @FindViewById(R.id.package_list_progress)
    private ProgressLayout package_list_progress;

    private NavSearchTypeFragmentAdapter navSearchTypeAdapter;

    private PopupWindow rangePpopupWindow;
    private PopupWindow sortPpopupWindow;
    private String searchType;
    private String poiType;
    private ProgressDialog loadingDialog;
    private String flagTag = MapListViewType.NEARBY.getStringValue();
    private int searchRange = 3000;
    private String searchSort = "推荐排序";
    private boolean isNextPage = false;
    private int lastItemIndex = 0;
    private List<PoiItemInfo> searchPoiList;
    private Resources res;
    private NavSearchTypePresenter navSearchTypePresenter;
    private AbstractMapActivity mapActivity;
    private MapHandler mapHandler;
    private FragmentManager fragmentManager;

    private AddMoreView addMoreView;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getArguments() != null) {
            searchType = getArguments().getString("searchType");
            poiType = getArguments().getString("poiType");
            navSearchTypePresenter = new NavSearchTypePresenter(mapActivity.getScheduler(), mapActivity, mapHandler);
            navSearchTypePresenter.setView(this);
        }
        if (isFirstLoad()) {
            initView();
            mapActivity.hideSoftInput();
            navSearchTypePresenter.search(searchType, poiType, searchRange);
            initBack();
        }

    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        res = activity.getResources();
        mapActivity = (AbstractMapActivity) activity;
        mapHandler = mapActivity.getMapHandler();
        fragmentManager = mapActivity.getSupportFragmentManager();
    }

    private void initBack() {
        frame_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goBack();
            }
        });
    }

    @Override
    public int getLayoutId() {
        return R.layout.nav_search_type;
    }

    public static NavSearchTypeFragment newInstance(String searchType, String poiType) {
        NavSearchTypeFragment navSearchTypeFragment = new NavSearchTypeFragment();
        Bundle bundle = new Bundle();
        bundle.putString("searchType", searchType);
        bundle.putString("poiType", poiType);
        navSearchTypeFragment.setArguments(bundle);

        return navSearchTypeFragment;
    }

    public void initView() {
        //搜索按钮
        right_btn.setVisibility(View.GONE);
        btn_regionalism.setText(res.getStringArray(R.array.range_list)[0]);
        btn_sort.setText(res.getStringArray(R.array.sort_list)[1]);

        edit_search_addressinfo.setText(searchType);
        edit_search_addressinfo.setFocusable(false);
        edit_search_addressinfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goBack();
            }
        });

//        edit_search_addressinfo.setOnEditorActionListener(new TextView.OnEditorActionListener() {
//            @Override
//            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
//                    search(edit_search_addressinfo.getText().toString().trim());
//                    return true;
//                }
//                return false;
//            }
//        });

        addMoreView = new AddMoreView(getContext());
        addMoreView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (addMoreView.isLoading())
                    return;
                try {
                    mapHandler.nextPageResult();
                    addMoreView.showLoading();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void showSearchResult(final List<PoiItemInfo> searchPoiList) {
        if (navSearchTypeAdapter == null) {
            isNextPage = mapHandler.IfhasNextPage();
            navSearchTypeAdapter = new NavSearchTypeFragmentAdapter(searchPoiList, mapActivity, -1, navSearchTypePresenter);
            search_type_listview.setAdapter(navSearchTypeAdapter);
            search_type_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    mapActivity.hideSoftInput();
                    BusinessUtil.sendReportByClickType(mapActivity, FunctionNameFindId.Categorysearch_searchresultclick.getStringValue());
                    navSearchTypePresenter.onItemClick(searchPoiList, position);
                }
            });
//            search_type_listview.setOnScrollListener(new AbsListView.OnScrollListener() {
//                @Override
//                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
//                    lastItemIndex = firstVisibleItem + visibleItemCount;
//                }
//
//                @Override
//                public void onScrollStateChanged(AbsListView view, int scrollState) {
//                    if (!isNextPage) {
//                        return;
//                    }
//                    if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE
//                            && lastItemIndex == navSearchTypeAdapter.getCount()) {
//                        try {
//                            mapHandler.nextPageResult();
//                            isNextPage = false;
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }
//            });
        } else {
            isNextPage = mapHandler.IfhasNextPage();
            navSearchTypeAdapter.setList(searchPoiList);
            navSearchTypeAdapter.notifyDataSetChanged();
        }
        setRootView(isNextPage);
    }

    private void setRootView(boolean isNextPage) {
        if (isNextPage) {
            if (search_type_listview.getFooterViewsCount() <= 0)
                search_type_listview.addFooterView(addMoreView);
        } else if (search_type_listview.getFooterViewsCount() > 0) {
            search_type_listview.removeFooterView(addMoreView);
        }
        addMoreView.showNormal();
    }

    @Override
    public void showSearchResultWithNodata() {
        AlertDialogUtil.showAlertDialog(mapActivity, R.string.dialog_warning, R.string.poi_no_search);
    }

    @Override
    public void switchToMapFragment(PoiItemInfo poiItemInfo) {
        mapActivity.showFragment(fragmentManager, NavMapFragment.class, NavMainFragment.class);
        NavActivity navActivity = (NavActivity) mapActivity;
        navActivity.showBottomView(poiItemInfo, true);
    }

    /**
     * @Title: showRegionalismListView
     * @Description: 显示搜索范围列表
     */
    public void showRegionalismListView() {
        final String[] rangedatas = mapActivity.getResources().getStringArray(R.array.range_list);

        ListView rangeListview = new ListView(mapActivity);
        rangeListview.setBackgroundColor(mapActivity.getResources().getColor(R.color.white_20));
        rangeListview.setDivider(new ColorDrawable(getResources().getColor(R.color.nav_line_color)));
        rangeListview.setDividerHeight(4);
        rangeListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0://三公里
                        BusinessUtil.sendReportByClickType(mapActivity,
                                FunctionNameFindId.Categorysearch_choose3km.getStringValue());
                        searchRange = 3000;
                        break;
                    case 1://五公里
                        BusinessUtil.sendReportByClickType(mapActivity,
                                FunctionNameFindId.Categorysearch_choose5km.getStringValue());
                        searchRange = 5000;
                        break;
                    case 2://全部范围
                        BusinessUtil.sendReportByClickType(mapActivity,
                                FunctionNameFindId.Categorysearch_choosewholecity.getStringValue());
                        searchRange = 10000;
                        flagTag = MapListViewType.NEARBY.getStringValue();
                        break;
                }
                btn_regionalism.setText(rangedatas[position]);
                rangePpopupWindow.dismiss();
                navSearchTypePresenter.search(searchType, poiType, searchRange);
            }
        });

        ArrayAdapter<String> rangeAdapter = new ArrayAdapter<String>(mapActivity, R.layout.nav_rangelist_item, rangedatas);
        rangeListview.setAdapter(rangeAdapter);

        rangePpopupWindow = new PopupWindow(rangeListview, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, false);
        rangePpopupWindow.setBackgroundDrawable(new ColorDrawable(Color.argb(50, 52, 53, 55)));
        rangePpopupWindow.setOutsideTouchable(false);
        rangePpopupWindow.setFocusable(true);
        rangePpopupWindow.showAsDropDown(search_view);
    }

    /**
     * @Title: showRegionalismListView
     * @Description: 显示推荐排序列表
     */
    public void showPreferSortListView() {
        final String[] sortDatas = mapActivity.getResources().getStringArray(R.array.sort_list);

        ListView sortDataListview = new ListView(mapActivity);
        sortDataListview.setBackgroundColor(mapActivity.getResources().getColor(R.color.white_20));
        sortDataListview.setDivider(new ColorDrawable(getResources().getColor(R.color.nav_line_color)));
        sortDataListview.setDividerHeight(4);
        sortDataListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0://三公里
                        searchRange = 3000;
                        break;
                    case 1://五公里
                        searchRange = 5000;
                        break;
                    case 2://全部范围
                        searchRange = 10000;
                        break;
                }
                btn_sort.setText(sortDatas[position]);
                sortPpopupWindow.dismiss();
                navSearchTypePresenter.search(searchType, poiType, searchRange);
            }
        });

        ArrayAdapter<String> rangeAdapter = new ArrayAdapter<String>(mapActivity, R.layout.nav_rangelist_item, sortDatas);
        sortDataListview.setAdapter(rangeAdapter);

        sortPpopupWindow = new PopupWindow(sortDataListview, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, false);
        sortPpopupWindow.setBackgroundDrawable(new ColorDrawable(Color.argb(50, 52, 53, 55)));
        sortPpopupWindow.setOutsideTouchable(false);
        sortPpopupWindow.setFocusable(true);
        sortPpopupWindow.showAsDropDown(search_view);
    }


    @OnClick({R.id.btn_regionalism})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.btn_regionalism://搜索范围
                if (sortPpopupWindow != null && sortPpopupWindow.isShowing()) {
                    sortPpopupWindow.dismiss();
                    showRegionalismListView();
                } else {
                    showRegionalismListView();
                }
                break;
//            case R.id.btn_sort:
//                if (rangePpopupWindow != null && rangePpopupWindow.isShowing()) {
//                    rangePpopupWindow.dismiss();
//                    showPreferSortListView();
//                } else {
//                    showPreferSortListView();
//                }
//                break;
        }
    }

    @Override
    public void showCommandLoading(boolean isShow) {
        if (isShow) {
            startActivity(new Intent(mapActivity, VehicleLoadingActivity.class));
        }
    }
}
